package org.flower.web.filter;

import org.flower.dao.impl.UserDaoImpl;
import org.flower.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/user/*")
public class UserLoginFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse) response;

        String uri = req.getRequestURI();

        if(uri.contains("/login.jsp")||uri.contains("/loginServlet")||
                uri.contains("/css/")||uri.contains("/js/")||uri.contains("/image/")){
            chain.doFilter(request,response);
        }else{
            User user = (User)req.getSession().getAttribute("user");
            if(user==null||user.equals("")){
                req.getRequestDispatcher("../login.jsp").forward(request,response);
            }else{
                boolean userState = new UserDaoImpl().findUserState(user.getId());
                if(userState){
                    chain.doFilter(request,response);
                }else{
                    res.getWriter().write(
                            "<script type=\"text/javascript\">alert('您的账号处于封禁状态！');setInterval(\"\",10);parent.location.href='" +
                                    req.getContextPath()
                                    + "/login.jsp'</script>");
                    res.getWriter().flush();
                    res.getWriter().close();
                }
            }
        }
    }
}
